package com.library.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.library.constant.MessageConstant;
import com.library.constant.StatusConstant;
import com.library.context.BaseContext;
import com.library.dto.PageQueryDTO;
import com.library.entity.Book;
import com.library.entity.BorrowHistory;
import com.library.entity.Category;
import com.library.exception.BorrowNotAllowedException;
import com.library.exception.DeletionNotAllowedException;
import com.library.exception.ReturnNotAllowedException;
import com.library.mapper.BookMapper;
import com.library.mapper.BorrowHistoryMapper;
import com.library.result.PageResult;
import com.library.service.BorrowService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@Slf4j
public class BorrowServiceImpl implements BorrowService {

    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private BorrowHistoryMapper borrowHistoryMapper;

    /**
     * 借书
     * @param bookId
     */
    @Override
    @Transactional
    public void borrow(Long bookId) {

        //查询图书剩余库存
        Book book = bookMapper.getBookByBookId(bookId);
        Integer count = book.getStock() - book.getBorrowed();
        //如果没有库存，抛出业务异常
        if(count == 0){
            throw new BorrowNotAllowedException(MessageConstant.BOOK_STOCK_NOT_ENOUGH);
        }
        //获得用户id
        Long userId = BaseContext.getCurrentId();
        //如果该用户已经借过，抛出业务异常
        if(borrowHistoryMapper.countByUserIdAndBookId(userId,bookId) > 0){
            throw new BorrowNotAllowedException(MessageConstant.BOOK_NOT_ALLOW_REPEAT_BORROW);
        }
        //否则增加借出数量，
        bookMapper.updateBorrowedBook(bookId);
        //创建借书历史记录
        BorrowHistory borrowHistory = BorrowHistory.builder()
                .bookId(bookId)
                .userId(userId)
                .bookTitle(book.getTitle())
                .borrowTime(LocalDateTime.now())
                .returnTime(null)
                .returnDeadline(LocalDateTime.now().plusMonths(1L))//借书一个月
                .status(StatusConstant.DISABLE)//默认未还书
                .build();

        borrowHistoryMapper.insert(borrowHistory);



    }

    /**
     * 还书
     * @param bookId
     */
    @Override
    @Transactional
    public void returnBook(Long bookId) {
        //获得当前用户id
        Long userId = BaseContext.getCurrentId();
        //更新借书历史记录
        BorrowHistory borrowHistory = BorrowHistory.builder()
                .userId(userId)
                .bookId(bookId)
                .returnTime(LocalDateTime.now())
                .status(StatusConstant.ENABLE)
                .build();
        int count = borrowHistoryMapper.update(borrowHistory);
        //更新图书库存
        if(count == 0){
            throw new ReturnNotAllowedException(MessageConstant.BOOK_NOT_ALLOW_REPEAT_RETURN);
        }
        bookMapper.updateReturnBook(bookId);

    }

    @Override
    public PageResult borrowHistory(Long userId, PageQueryDTO pageQueryDTO) {
        PageHelper.startPage(pageQueryDTO.getPage(),pageQueryDTO.getPageSize());
        //下一条sql进行分页，自动加入limit关键字分页
        Page<BorrowHistory> page = borrowHistoryMapper.pageQuery(pageQueryDTO, userId);

        return new PageResult(page.getTotal(), page.getResult());
    }
}
